package com.jiezuo.flowable.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.google.common.collect.Maps;
import com.jiezuo.auth.entity.User;
import com.jiezuo.common.enums.CustomUserTypeEnum;
import com.jiezuo.common.exception.BusinessRuntimeException;
import com.jiezuo.common.util.ContextHolderUtils;
import com.jiezuo.common.util.DateTimeUtil;
import com.jiezuo.common.util.JsonUtils;
import com.jiezuo.common.util.StringUtil;
import com.jiezuo.common.vo.Result;
import com.jiezuo.flowable.entity.*;
import com.jiezuo.flowable.mapper.CommonMapper;
import com.jiezuo.flowable.service.*;
import lombok.extern.slf4j.Slf4j;
import org.flowable.bpmn.model.*;
import org.flowable.bpmn.model.Process;
import org.flowable.engine.ProcessEngine;
import org.flowable.engine.history.HistoricProcessInstance;
import org.flowable.task.api.Task;
import org.flowable.task.api.TaskQuery;
import org.flowable.ui.modeler.domain.Model;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.DecimalFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @description
 * @author 庞留杰
 * @date 2023/8/4 11:23
 * @version V1.0
 **/
@Slf4j
@Service
@Transactional
public class CommonServiceImpl implements CommonService {

    @Autowired
    CommonMapper commonMapper;
    @Autowired
    MyFormInformationService informationService;
    @Autowired
    MyFormDesignService formDesignService;
    @Autowired
    ProcessEngine processEngine;
    @Autowired
    UserProcessInstanceService processInstanceService;
    @Autowired
    UserTaskService taskService;
//    @Autowired
//    FinanceClient financeClient;


    @Override
    public String start(Map<String, Object> params) {
        String businessKey = String.valueOf(params.get("businessKey"));
        String processDefinitionKey = String.valueOf(params.get("processDefinitionKey"));
        String businessName = String.valueOf(params.get("businessName"));
        String message = params.get("message") != null ? String.valueOf(params.get("message")) : "";
        Object obj = params.get("variables");
        Map<String, Object> variables = obj == null ? Maps.newHashMap() : (Map<String, Object>) obj;
        User user = ContextHolderUtils.currentUser();
        //发起流程
        ProcessInstanceAddQuery processInstance = new ProcessInstanceAddQuery();
        processInstance.setProcessDefinitionKey(processDefinitionKey);//流程KEY
        processInstance.setBusinessKey(businessKey);//业务ID
        processInstance.setBusinessName(businessName);//业务名称
        processInstance.setVariables(variables);//流程变量
        String processInstanceId = processInstanceService.startByKey(user, processInstance);
        /**
         * isIncludeSponsor
         * 1. 为空，默认包含
         * 2. 为 true, 包含
         * 3. 为 false，不包含
         * */
        Boolean isIncludeSponsor = !StringUtil.isNotEmpty(String.valueOf(params.get("isIncludeSponsor")))
                || Boolean.valueOf(String.valueOf(params.get("isIncludeSponsor")));
        if (isIncludeSponsor) {
            // 我的待办
            Task task = processEngine.getTaskService().createTaskQuery().processInstanceId(processInstanceId).singleResult();
            String taskId = task.getId();
            //签收任务
            TaskExecuteQuery claimMap = new TaskExecuteQuery();
            claimMap.setTaskId(taskId); //taskId
            claimMap.setAction("claim");//执行任务类型
            claimMap.setAssignee(user.getId());//受让人/执行人
            claimMap.setVariables(variables);
            taskService.executeTask(claimMap);
            //添加评论-审核意见
            if (StringUtil.isNotEmpty(message)) {
                CommentAddQuery commentMap = new CommentAddQuery();
                commentMap.setTaskId(taskId); //任务ID
                commentMap.setUserId(user.getId());  //用户id
                commentMap.setProcessInstanceId(processInstanceId);  //用户id
                commentMap.setMessage(message); //备注信息
                taskService.addComments(commentMap);
            }
            //执行任务
            TaskExecuteQuery executeMap = new TaskExecuteQuery();
            executeMap.setTaskId(taskId); //taskId
            executeMap.setAction("complete");//执行任务类型
            executeMap.setVariables(variables);
            //先添加评论，后执行任务。因为task执行后就会消失，评论便无法找到当前的task
            taskService.executeTask(executeMap);
        }
        return processInstanceId;
    }

    @Override
    public void execute(Map<String, Object> params) {
        String taskId = params.get("taskId") != null ? String.valueOf(params.get("taskId")) : null;
        String message = params.get("message") != null ? String.valueOf(params.get("message")) : "";
        if (!StringUtil.isNotEmpty(taskId)) {
            log.error("流程审核失败，TaskId：{}", taskId);
            throw new BusinessRuntimeException("当前用户无操作权限，请联系管理员");
        }
        Object obj = params.get("variables");
        Map<String, Object> variables = obj == null ? Maps.newHashMap() : (Map<String, Object>) obj;
        User user = ContextHolderUtils.currentUser();
        //签收任务
        TaskExecuteQuery claimMap = new TaskExecuteQuery();
        claimMap.setTaskId(taskId); //taskId
        claimMap.setAction("claim");//执行任务类型
        claimMap.setAssignee(user.getId());//受让人/执行人
        claimMap.setVariables(variables);
        taskService.executeTask(claimMap);
        if (StringUtil.isNotEmpty(message)) {
            //添加评论-审核意见
            CommentAddQuery commentMap = new CommentAddQuery();
            commentMap.setTaskId(taskId); //任务ID
            commentMap.setUserId(user.getId());  //用户id
            commentMap.setMessage(message); //备注信息
            taskService.addComments(commentMap);
        }
        //执行任务
        TaskExecuteQuery executeMap = new TaskExecuteQuery();
        executeMap.setTaskId(taskId); //taskId
        executeMap.setAction("complete");//执行任务类型
        executeMap.setVariables(variables);
        //先添加评论，后执行任务。因为task执行后就会消失，评论便无法找到当前的task
        taskService.executeTask(executeMap);
    }

    @Override
    public List<String> apply(String processDefinitionKey) {
        User user = ContextHolderUtils.currentUser();
        String userId = user.getId();
        List<String> ids = commonMapper.apply(userId, processDefinitionKey);
        return ids;
    }

    @Override
    public List<Map<String, Object>> todo(String processDefinitionKey) {
        Map<String, Object> map = getGroupIdInfo();
        String userId = String.valueOf(map.get("userId"));
        String[] groupId_1 = (String[]) map.get("groupId_1");
        String[] groupId_2 = (String[]) map.get("groupId_2");
        List<Map<String, Object>> ids = commonMapper.todo(userId, groupId_1, groupId_2, processDefinitionKey);
        return ids;
    }

    public Map<String, Object> getGroupIdInfo() {
        User user = ContextHolderUtils.currentUser();
        // 旧
        String groups = ContextHolderUtils.getFlowGroupIds();
        String userId = user.getId();
        String[] groupId_1 = groups.split(",");
        //-----------------------------------------------------------
        // 新
        // 6部门-岗位
        if (StringUtil.isNotEmpty(user.getPositions())) {
            ArrayList<String> dps = new ArrayList<>();//部门岗位
            String[] positions = user.getPositions().split(",");
            for (String position : positions) {
                String s = CustomUserTypeEnum.DEPT_POST.getKey() + "_" + user.getMain_dept() + "_" + position;
                dps.add(s);
            }
            dps.addAll(Arrays.asList(groupId_1));
            // 岗位组 --> 单独处理，岗位组中的岗位不在受部门影响
            List<String> positionGroupIds = commonMapper.findPositionGroupIdsByPositions(user.getPositions().split(","));
            if (positionGroupIds.size() > 0) {
                positionGroupIds = positionGroupIds.stream().map(e -> CustomUserTypeEnum.GROUP.getKey() + "_" + e).collect(Collectors.toList());
                // list.addAll(positionGroupIds);
                dps.addAll(positionGroupIds);
            }

            groupId_1 = dps.toArray(new String[dps.size()]);
        }
        // 1部门，2岗位，3岗位组，4岗位等级，5部门岗位
        ArrayList<String> list = new ArrayList<>();
        // 部门
        List<String> departIds = commonMapper.findDepartIdsByUserId(user.getId());
        departIds = departIds.stream().map(e -> CustomUserTypeEnum.DEPT.getKey() + "_" + e).collect(Collectors.toList());
        list.addAll(departIds);
        if (StringUtil.isNotEmpty(user.getPositions())) {
            // 岗位
            List<String> positionIds = Arrays.stream(user.getPositions().split(",")).map(e -> CustomUserTypeEnum.POST.getKey() + "_" + e).collect(Collectors.toList());
            list.addAll(positionIds);
            // 岗位等级
            List<String> positionLevels = commonMapper.findPositionLevelIdsByPositions(user.getPositions().split(","));
            if (positionLevels.size() > 0) {
                positionLevels = positionLevels.stream().map(e -> CustomUserTypeEnum.LEVEL.getKey() + "_" + e).collect(Collectors.toList());
                list.addAll(positionLevels);
            }
        }
        String[] groupId_2 = list.toArray(new String[list.size()]);
        Map<String, Object> map = new HashMap<>();
        map.put("userId", userId);
        map.put("groupId_1", groupId_1);
        map.put("groupId_2", groupId_2);
        return map;
    }

    @Override
    public Map<String, Object> message() {
        List<Map<String, Object>> allMessage = new ArrayList<>();
//        Result<JSONArray> reportResult = financeClient.myToDoMessage();
//        JSONArray arr = reportResult.getResult();
//        for (Object o : arr) {
//            Map<String, Object> obj = JsonUtils.objToMap(o);
//            JSONArray childs = (JSONArray) obj.get("children");
//            for (Object o1 : childs) {
//                Map<String, Object> obj1 = JsonUtils.objToMap(o1);
//                Map<String, Object> sub = new HashMap<>();
//                sub.put("id", "");
//                sub.put("count", obj1.get("total"));
//                sub.put("icon", obj1.get("icon"));
//                sub.put("name", obj1.get("title"));
//                sub.put("module", obj1.get("name"));
//                sub.put("router", obj1.get("url"));
//                sub.put("created_time", DateTimeUtil.format(new Date(), DateTimeUtil.DATE));
//                allMessage.add(sub);
//            }
//        }
        //-------------------------------------
        Map<String, Object> map = getGroupIdInfo();
        String userId = String.valueOf(map.get("userId"));
        String[] groupId_1 = (String[]) map.get("groupId_1");
        String[] groupId_2 = (String[]) map.get("groupId_2");
        List<String> excludeId = commonMapper.findExcludeId();
        List<Map<String, Object>> flowMessage = commonMapper.message(userId, groupId_1, groupId_2, excludeId);
        allMessage.addAll(flowMessage);
        //-------------------------------------
        JSONArray blocks = new JSONArray();
        Set<String> classifys = allMessage.stream().map(it -> String.valueOf(it.get("name")).trim()).collect(Collectors.toSet());
        for (String classify : classifys) {
            List<Map<String, Object>> list = allMessage.stream().filter(it -> classify.equals(String.valueOf(it.get("name")))).collect(Collectors.toList());
            long size = list.stream().mapToLong(it -> Long.parseLong(String.valueOf(it.get("count")))).sum();
            JSONObject obj = new JSONObject();
            obj.put("classify", classify);
            obj.put("size", size);
            JSONArray childrens = new JSONArray();
            for (Map<String, Object> child : list) {
                JSONObject obj1 = new JSONObject();
                obj1.put("total", child.get("count"));
                obj1.put("icon", child.get("icon"));
                obj1.put("name", child.get("module"));
                obj1.put("title", child.get("name"));
                obj1.put("url", child.get("router"));
                childrens.add(obj1);
            }
            obj.put("children", childrens);
            blocks.add(obj);
        }
        //-------------------------------------
        Integer sum = 0;
        // 计算总数
        for (Map<String, Object> msg : allMessage) {
            int i = msg.get("count") != null ? Integer.valueOf(msg.get("count") + "") : 0;
            sum += i;
        }
        Map<String, Object> result = new HashMap<>();
        result.put("blocks", blocks);
        result.put("details", allMessage);
        result.put("sum", sum);
        return result;
    }

    @Override
    public List<String> done(String processDefinitionKey) {
        User user = ContextHolderUtils.currentUser();
        String userId = user.getId();
        List<String> ids = commonMapper.done(userId, processDefinitionKey);
        return ids;
    }

    @Override
    public void withdraw(Map<String, Object> params) {
        User user = ContextHolderUtils.currentUser();
        String processInstanceId = String.valueOf(params.get("processInstanceId"));//需要跳转的步骤的id
        String currentTaskKey = String.valueOf(params.get("currentTaskKey")); //当前步骤的id
        String targetTaskKey = String.valueOf(params.get("targetTaskKey")); //目标任务定义Key
        String message = String.valueOf(params.get("message")); //备注
        //意见
        if (StringUtil.isNotEmpty(message)) {
            CommentAddQuery commentMap = new CommentAddQuery();
            commentMap.setUserId(user.getId());  //用户id
            commentMap.setProcessInstanceId(processInstanceId);  //用户id
            commentMap.setMessage(message); //备注信息
            taskService.addComments2(commentMap); //添加评论
        }
        String taskId = taskService.getTaskIdByProcessInstanceId(processInstanceId);
        // 回退前，先签收
        TaskExecuteQuery claimMap = new TaskExecuteQuery();
        claimMap.setTaskId(taskId); //taskId
        claimMap.setAction("claim");//执行任务类型
        claimMap.setAssignee(user.getId());//受让人/执行人
        claimMap.setVariables(Maps.newHashMap());
        taskService.executeTask(claimMap);
        // 工作流回退
        TaskFallbackQuery taskFallbackQuery = new TaskFallbackQuery();
        taskFallbackQuery.setProcessInstanceId(processInstanceId);
        taskFallbackQuery.setCurrentTaskKey(currentTaskKey);
        taskFallbackQuery.setTargetTaskKey(targetTaskKey);
        taskService.withdraw(taskFallbackQuery);
    }

    @Override
    public String getTaskIdByProcessInstanceId(String processInstanceId) {
        // 支持并行网关
        TaskQuery taskQuery = processEngine.getTaskService().createTaskQuery().processInstanceId(processInstanceId);
        if (ContextHolderUtils.currentUser() != null) {
            String userId = ContextHolderUtils.currentUser().getId();
            taskQuery.taskCandidateOrAssigned(userId);
            // String group_ids = ContextHolderUtils.getGroupIds();
            String group_ids = ContextHolderUtils.getFlowGroupIds();
            if (StringUtil.isNotEmpty(group_ids)) {
                String[] split = group_ids.split(",");
                List<String> groupIds = Arrays.asList(split);
                if (groupIds.size() > 0) {
                    taskQuery.taskCandidateGroupIn(groupIds);
                }
            }
        }
        Task task = taskQuery.active().singleResult();
        String taskId = "";
        if (task != null) {
            taskId = task.getId();
        }
        return taskId;
    }

    @Override
    public List<User> findTodoPersonsByProcessInstanceId(String processInstanceId) {
        return commonMapper.findTodoPersonsByProcessInstanceId(processInstanceId);
    }

    @Override
    public void deleteProcessInstanceId(String processInstanceId) {
        boolean completed = taskService.isCompletedByProcessInstanceId(processInstanceId);
        if (!completed) {//流程结束，不允许再删除在途流程，否则会报错
            // 删除运行中的流程
            processEngine.getRuntimeService().deleteProcessInstance(processInstanceId, "删除流程");
        }
        // 流程结束可以通过下面的方法删除，否则报错
        processEngine.getHistoryService().deleteHistoricProcessInstance(processInstanceId);
    }

    @Override
    public List<Map<String, String>> findAllUser() {
        return commonMapper.findAllUser();
    }

    @Override
    public List<Map<String, String>> findAllDepart() {
        String key = CustomUserTypeEnum.DEPT.getKey() + "_";
        return commonMapper.findAllDepart(key);
    }

    @Override
    public List<Map<String, String>> findAllPosition() {
        String key = CustomUserTypeEnum.POST.getKey() + "_";
        return commonMapper.findAllPosition(key);
    }

    @Override
    public List<Map<String, String>> findAllPositionGroup() {
        String key = CustomUserTypeEnum.GROUP.getKey() + "_";
        return commonMapper.findAllPositionGroup(key);
    }

    @Override
    public List<Map<String, String>> findAllPositionLevel() {
        String key = CustomUserTypeEnum.LEVEL.getKey() + "_";
        return commonMapper.findAllPositionLevel(key);
    }

    @Override
    public void draftForm(Map<String, Object> params) {
        Object formData = params.get("data");
        QueryWrapper<MyFormDesign> queryWrapper = new QueryWrapper();
        queryWrapper.eq("is_delete", "0");
        queryWrapper.eq("code", params.get("formKey"));
        List<MyFormDesign> list = formDesignService.list(queryWrapper);
        MyFormDesign myFormDesign = list.get(0);
        MyFormInformation information = new MyFormInformation();
        if (params.get("informationId") != null) {
            String id = params.get("informationId") != null ? String.valueOf(params.get("informationId")) : null;
            information.setId(id);
            MyFormInformation byId = informationService.getById(id);
            information.setBusiness_id(byId.getBusiness_id());
            JSONObject jsonObject = JSONObject.parseObject(formData + "");
            jsonObject.put("id", byId.getBusiness_id());// 防止业务ID为空
            formData = jsonObject;
        }
//        todo 待优化...........
//        if(!StringUtil.isNotEmpty(information.getNumber())){
//            String number = getNumber();
//            information.setNumber(number);
//        }
        information.setNumber(null);
        information.setCode(myFormDesign.getCode());
        information.setContent(myFormDesign.getContent());
        information.setVersion(myFormDesign.getVersion());
        information.setData(formData + "");
        information.setProcess_instance_id(null);
        // boolean save = informationService.save(information);
//        Result result = financeClient.draft(information);
//        if (!result.isSuccess()) {
//            throw new BusinessRuntimeException(result.getMessage());//调用失败，抛出异常
//        }
//        System.out.println("result = " + result);

    }

    @Override
    public void temporarySaveForm(Map<String, Object> params) {
        Object formData = params.get("data");
        MyFormInformation information = new MyFormInformation();
        if (params.get("informationId") != null) {
            String id = params.get("informationId") != null ? String.valueOf(params.get("informationId")) : null;
            information = informationService.getById(id);
            JSONObject jsonObject = JSONObject.parseObject(formData + "");
            jsonObject.put("id", information.getBusiness_id());// 防止业务ID为空
            formData = jsonObject;
        }
        information.setData(formData + "");
        boolean save = informationService.saveOrUpdate(information);
//        Result result = financeClient.temporarySave(information);
//        if (!result.isSuccess()) {
//            throw new BusinessRuntimeException(result.getMessage());//调用失败，抛出异常
//        }
    }

    @Override
    public String startForm(Map<String, Object> params) {
        User user = ContextHolderUtils.currentUser();
        String processDefinitionKey = String.valueOf(params.get("processDefinitionKey"));
        Model model = commonMapper.findModelByKey(processDefinitionKey);
        String number = getNumber();
        params.put("businessKey", number);
        params.put("businessName", model.getName() + "【" + number + "】");
        // params.put("message", "您发起了一个“" + params.get("name") + "”流程，流程编号【" + number + "】");
        // params.put("message", params.get("name") + "【" + number + "】");
        Object formData = params.get("data");
        Map<String, Object> variables = JsonUtils.jsonToMap((String) formData);//流程中的数据需要保存到表单，可能会用于网关的条件
        params.put("variables", variables);
        // 发起流程
        // String processInstanceId = this.start(params);
        String processInstanceId = startProcess(params, user);// 发起流程
        // 处理流程表单数据
        QueryWrapper<MyFormDesign> queryWrapper = new QueryWrapper();
        queryWrapper.eq("is_delete", "0");
        queryWrapper.eq("code", params.get("formKey"));
        List<MyFormDesign> list = formDesignService.list(queryWrapper);
        MyFormDesign myFormDesign = list.get(0);
        MyFormInformation information = new MyFormInformation();
        if (params.get("informationId") != null) {
            String id = params.get("informationId") != null ? String.valueOf(params.get("informationId")) : null;
            information.setId(id);
            MyFormInformation byId = informationService.getById(id);
            information.setBusiness_id(byId.getBusiness_id());
            JSONObject jsonObject = JSONObject.parseObject(formData + "");
            jsonObject.put("id", byId.getBusiness_id());
            formData = jsonObject;
        }
        information.setNumber(number);
        information.setCode(myFormDesign.getCode());
        information.setContent(myFormDesign.getContent());
        information.setVersion(myFormDesign.getVersion());
        information.setData(formData + "");
        information.setProcess_instance_id(processInstanceId);
        boolean save = informationService.saveOrUpdate(information);
        executionProcess(params, user, processInstanceId);// 执行流程
        return processInstanceId;
    }

    //发起流程，如果不拆开，第一步后面无法处理消息
    String startProcess(Map<String, Object> params, User user) {
        String businessKey = String.valueOf(params.get("businessKey"));
        String processDefinitionKey = String.valueOf(params.get("processDefinitionKey"));
        String businessName = String.valueOf(params.get("businessName"));
        Object obj = params.get("variables");
        Map<String, Object> variables = obj == null ? Maps.newHashMap() : (Map<String, Object>) obj;
        //发起流程
        ProcessInstanceAddQuery processInstance = new ProcessInstanceAddQuery();
        processInstance.setProcessDefinitionKey(processDefinitionKey);//流程KEY
        processInstance.setBusinessKey(businessKey);//业务ID
        processInstance.setBusinessName(businessName);//业务名称
        processInstance.setVariables(variables);//流程变量
        String processInstanceId = processInstanceService.startByKey(user, processInstance);
        return processInstanceId;
    }

    //发起流程
    void executionProcess(Map<String, Object> params, User user, String processInstanceId) {
        String message = params.get("message") != null ? String.valueOf(params.get("message")) : "";
        Object obj = params.get("variables");
        Map<String, Object> variables = obj == null ? Maps.newHashMap() : (Map<String, Object>) obj;
        /**
         * isIncludeSponsor
         * 1. 为空，默认包含
         * 2. 为 true, 包含
         * 3. 为 false，不包含
         * */
        Boolean isIncludeSponsor = !StringUtil.isNotEmpty(String.valueOf(params.get("isIncludeSponsor")))
                || Boolean.valueOf(String.valueOf(params.get("isIncludeSponsor")));
        if (isIncludeSponsor) {
            // 我的待办
            Task task = processEngine.getTaskService().createTaskQuery().processInstanceId(processInstanceId).singleResult();
            String taskId = task.getId();
            //签收任务
            TaskExecuteQuery claimMap = new TaskExecuteQuery();
            claimMap.setTaskId(taskId); //taskId
            claimMap.setAction("claim");//执行任务类型
            claimMap.setAssignee(user.getId());//受让人/执行人
            claimMap.setVariables(variables);
            taskService.executeTask(claimMap);
            //添加评论-审核意见
            if (StringUtil.isNotEmpty(message)) {
                CommentAddQuery commentMap = new CommentAddQuery();
                commentMap.setTaskId(taskId); //任务ID
                commentMap.setUserId(user.getId());  //用户id
                commentMap.setProcessInstanceId(processInstanceId);  //用户id
                commentMap.setMessage(message); //备注信息
                taskService.addComments(commentMap);
            }
            //执行任务
            TaskExecuteQuery executeMap = new TaskExecuteQuery();
            executeMap.setTaskId(taskId); //taskId
            executeMap.setAction("complete");//执行任务类型
            executeMap.setVariables(variables);
            //先添加评论，后执行任务。因为task执行后就会消失，评论便无法找到当前的task
            taskService.executeTask(executeMap);
        }
    }


    @Override
    public void executeForm(Map<String, Object> params) {
        String informationId = String.valueOf(params.get("informationId"));
        Object formData = params.get("data");
        Map<String, Object> variables = JsonUtils.jsonToMap((String) formData);//流程中的数据需要保存到表单，可能会用于网关的条件
        // Map<String, Object> variables = new HashMap<>();
        // variables.put("isAgree", Boolean.valueOf(params.get("isAgree") + ""));
        // variables.put("message", params.get("message"));
        String startUserId = getStartUserIdByTaskId(String.valueOf(params.get("taskId")));
        Map<String, String> dept = commonMapper.findMainDeptByUserId(startUserId);
        variables.put("initiator", startUserId);//发起人
        variables.put("initiatorDept", dept.get("main_dept"));//发起人部门
        variables.put("initiatorDeptAncestors", Arrays.asList(dept.get("dept_ancestors").split(",")));//发起人部门祖级
        // 从表单中抓取意见信息
        if (params.get("taskId") != null) {
            approvalOpinion(params);
        }
        params.put("variables", variables);
        this.execute(params);
        MyFormInformation information = new MyFormInformation();
        information.setId(informationId);
        if (informationId != null) {
            String id = informationId;
            information.setId(id);
            MyFormInformation byId = informationService.getById(id);
            information.setBusiness_id(byId.getBusiness_id());
            JSONObject jsonObject = JSONObject.parseObject(formData + "");
            jsonObject.put("id", byId.getBusiness_id());
            formData = jsonObject;
        }
        information.setData(formData + "");
        boolean update = informationService.updateById(information);
        // 流程存放数据方法
        // ProcessInstance processInstance = formService.submitTaskFormData( taskId, properties);
    }

    // 处理审批意见信息
    void approvalOpinion(Map<String, Object> params) {
        String taskId = params.get("taskId") != null ? String.valueOf(params.get("taskId")) : null;
        Task task = processEngine.getTaskService().createTaskQuery().taskId(taskId).singleResult();
        if (task == null) {
            return;
        }
        String processDefinitionId = task.getProcessDefinitionId();
        String taskDefinitionKey = task.getTaskDefinitionKey();
        BpmnModel bpmnModel = processEngine.getRepositoryService().getBpmnModel(processDefinitionId);
        if (bpmnModel.getProcesses().size() > 0) {
            Process process = bpmnModel.getProcesses().get(0);
            Collection<FlowElement> flowElements = process.getFlowElements();
            if (flowElements.size() > 0) {
                for (FlowElement flowElement : flowElements) {
                    if (flowElement instanceof UserTask) {
                        UserTask userTask = (UserTask) flowElement;
                        Map<String, List<ExtensionAttribute>> attributes = userTask.getAttributes();
                        if (userTask.getId().equals(taskDefinitionKey)) {
                            if (attributes != null && attributes.size() > 0) {
                                List<ExtensionAttribute> commentField = attributes.get("commentField");
                                if (commentField != null && commentField.size() > 0) {
                                    for (ExtensionAttribute attribute : commentField) {
                                        Object formData = params.get("data");
                                        JSONObject jsonObject = JSONObject.parseObject(formData + "");
                                        if (jsonObject != null) {
                                            Object opinion = jsonObject.get(attribute.getValue());
                                            params.put("message", opinion);
                                        }

                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }


    // 编号生成规则 年月日+ 5位数字
    private String getNumber() {
        QueryWrapper<MyFormInformation> queryWrapper = new QueryWrapper();
        queryWrapper.eq("is_delete", "0");
        // 当天的开始时间
        LocalDateTime startOfDay = LocalDateTime.of(LocalDate.now(), LocalTime.MIN);
        LocalDateTime endOfDay = LocalDateTime.of(LocalDate.now(), LocalTime.MAX);
        queryWrapper.ge("created_time", startOfDay);
        queryWrapper.lt("created_time", endOfDay);
        long count = informationService.count(queryWrapper);
        DecimalFormat decimalFormat = new DecimalFormat("00000");
        String num = decimalFormat.format(count + 1);
        return DateTimeUtil.format(new Date(), DateTimeUtil.YEAR_TO_DATE) + num;
    }

    // 通过流程实例ID获取发起人ID
    @Override
    public String getStartUserIdByProcessInstanceId(String processInstanceId) {
        HistoricProcessInstance hi = processEngine.getHistoryService().createHistoricProcessInstanceQuery()
                .processInstanceId(processInstanceId)
                .singleResult();
        return hi.getStartUserId();//发起人ID
    }

    @Override
    public List<Map<String, Object>> apply2(String processDefinitionKey) {
        User user = ContextHolderUtils.currentUser();
        String userId = user.getId();
        List<Map<String, Object>> map = commonMapper.apply2(userId, processDefinitionKey);
        return map;
    }

    @Override
    public List<Map<String, Object>> todo2(String processDefinitionKey) {
        return this.todo(processDefinitionKey);
    }

    @Override
    public List<Map<String, Object>> done2(String processDefinitionKey) {
        User user = ContextHolderUtils.currentUser();
        String userId = user.getId();
        List<Map<String, Object>> map = commonMapper.done2(userId, processDefinitionKey);
        return map;
    }

    @Override
    public String getStartUserIdByTaskId(String taskId) {
        Task task = processEngine.getTaskService().createTaskQuery().taskId(taskId).singleResult();
        String processInstanceId = task.getProcessInstanceId();
        HistoricProcessInstance hi = processEngine.getHistoryService().createHistoricProcessInstanceQuery()
                .processInstanceId(processInstanceId)
                .singleResult();
        return hi.getStartUserId();//发起人ID
    }

    @Override
    public List<Map<String, String>> findTodoInfoByProcessInstanceId(String processInstanceId) {
        List<Map<String, String>> infos = commonMapper.findInfosByProcessInstanceId(processInstanceId);
        List<Map<String, String>> groups = commonMapper.findGroupIdsByProcessInstanceId(processInstanceId);
        if (groups.size() > 0) {
            for (Map<String, String> group : groups) {
                String groupId = group.get("GROUP_ID_");
                String task_name = group.get("NAME_");
                String[] split = groupId.split("_");
                int length = split.length;
                Map<String, String> entity = new HashMap<>();
                entity.put("task_name", task_name);
//                entity.put("processInstanceId", processInstanceId);
                if (length == 1) {
                    String s = split[0];
                    entity.put("type", "0");
                    entity.put("param1", s);
                } else if (length == 3) {
                    String s1 = split[0];
                    String s2 = split[1];
                    String s3 = split[2];
                    entity.put("type", s1);
                    entity.put("param1", s2);
                    entity.put("param2", s3);
                } else {
                    String s1 = split[0];
                    String s2 = split[1];
                    entity.put("type", s1);
                    entity.put("param1", s2);
                }
                List<Map<String, String>> infos1 = commonMapper.findInfos(entity);
                if (infos1.size() > 0) {
                    infos.addAll(infos1);
                }
            }
        }
        return infos;
    }

    @Override
    public void crossNodeRejection(Map<String, Object> map) {
        User user = ContextHolderUtils.currentUser();
        String informationId = String.valueOf(map.get("informationId"));
        String taskId = String.valueOf(map.get("taskId"));
        String processInstanceId = String.valueOf(map.get("process_instance_id"));
        String currentTaskKey = String.valueOf(map.get("currentTaskKey"));
        String targetTaskKey = String.valueOf(map.get("targetTaskKey"));
        String data = String.valueOf(map.get("data"));
        String comment = String.valueOf(map.get("comment"));
        MyFormInformation myFormInformation = new MyFormInformation();
        myFormInformation.setId(informationId);
        myFormInformation.setData(data);
        informationService.updateById(myFormInformation);
        //意见
        if (StringUtil.isNotEmpty(comment)) {
            CommentAddQuery commentAdd = new CommentAddQuery();
            commentAdd.setUserId(user.getId());  //用户id
            commentAdd.setTaskId(taskId);  //TaskId
            commentAdd.setProcessInstanceId(processInstanceId);  //用户id
            commentAdd.setMessage(comment); //备注信息
            //添加评论
            taskService.addComments3(commentAdd);
        }
        //签收任务
        TaskExecuteQuery claimMap = new TaskExecuteQuery();
        claimMap.setTaskId(taskId); //taskId
        claimMap.setAction("claim");//执行任务类型
        claimMap.setAssignee(user.getId());//受让人/执行人
        taskService.executeTask(claimMap);
        // 回退任务
        // Map<String, String> result = taskService.rollback3(processInstanceId);
        Map<String, String> param = new HashMap<>();
        param.put("processInstanceId", processInstanceId);
        param.put("taskId", taskId);
        param.put("currentTaskKey", currentTaskKey);
        param.put("targetTaskKey", targetTaskKey);
        Map<String, String> result = taskService.rollback5(param);
        String to = result.get("to");
        String toName = result.get("toName");
        String from = result.get("from");
        String fromName = result.get("fromName");
        MyFormInformation byId = informationService.getById(informationId);
        Map map1 = new HashMap();
        map1.put("processInstanceId", processInstanceId);
        map1.put("currentActivityId", from);
        map1.put("currentActivityName", fromName);
        map1.put("activityId", to);
        map1.put("activityName", toName);
//        Result reject = financeClient.reject(map1);
//        if (!reject.isSuccess()) {
//            throw new BusinessRuntimeException(reject.getMessage());//调用失败，抛出异常
//        }
    }

    @Override
    public void reject(Map<String, Object> map) {
        User user = ContextHolderUtils.currentUser();
        String informationId = String.valueOf(map.get("informationId"));
        String taskId = String.valueOf(map.get("taskId"));
        String processInstanceId = String.valueOf(map.get("process_instance_id"));
        String data = String.valueOf(map.get("data"));
        String comment = String.valueOf(map.get("comment"));
        MyFormInformation myFormInformation = new MyFormInformation();
        myFormInformation.setId(informationId);
        myFormInformation.setData(data);
        informationService.updateById(myFormInformation);
        //意见
        if (StringUtil.isNotEmpty(comment)) {
            CommentAddQuery commentAdd = new CommentAddQuery();
            commentAdd.setUserId(user.getId());  //用户id
            commentAdd.setTaskId(taskId);  //TaskId
            commentAdd.setProcessInstanceId(processInstanceId);  //用户id
            commentAdd.setMessage(comment); //备注信息
            //添加评论
            taskService.addComments3(commentAdd);
        }
        //签收任务
        TaskExecuteQuery claimMap = new TaskExecuteQuery();
        claimMap.setTaskId(taskId); //taskId
        claimMap.setAction("claim");//执行任务类型
        claimMap.setAssignee(user.getId());//受让人/执行人
        taskService.executeTask(claimMap);
        // 回退任务
        // Map<String, String> result = taskService.rollback3(processInstanceId);
        Map<String, String> result = taskService.rollback4(processInstanceId, taskId);
        String to = result.get("to");
        String toName = result.get("toName");
        String from = result.get("from");
        String fromName = result.get("fromName");
        MyFormInformation byId = informationService.getById(informationId);
        Map map1 = new HashMap();
        map1.put("processInstanceId", processInstanceId);
        map1.put("currentActivityId", from);
        map1.put("currentActivityName", fromName);
        map1.put("activityId", to);
        map1.put("activityName", toName);
//        Result reject = financeClient.reject(map1);
//        if (!reject.isSuccess()) {
//            throw new BusinessRuntimeException(reject.getMessage());//调用失败，抛出异常
//        }
    }


    @Override
    public void deleteFormAndFlow(Map<String, Object> params) {
        String processInstanceId = params.get("processInstanceId") != null ? String.valueOf(params.get("processInstanceId")) : null;
        String businessId = params.get("businessId") != null ? String.valueOf(params.get("businessId")) : null;
        String formCode = params.get("formCode") != null ? String.valueOf(params.get("formCode")) : null;
        //清理动态表单
        UpdateWrapper<MyFormInformation> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("is_delete", "0");
        updateWrapper.eq("code", formCode);
        if (StringUtil.isNotEmpty(processInstanceId)) updateWrapper.eq("process_instance_id", processInstanceId);
        if (StringUtil.isNotEmpty(businessId)) updateWrapper.eq("business_id", businessId);
        updateWrapper.set("is_delete", "1");
        informationService.update(updateWrapper);
        //清理流程
        if (StringUtil.isNotEmpty(processInstanceId)) {
            this.deleteProcessInstanceId(processInstanceId);
        }
    }

}
